export default defineNuxtPlugin(() => {
  if (process.client) {
    const win = window as unknown as {
      addEventListener: typeof window.addEventListener
      removeEventListener: typeof window.removeEventListener
      onunload: ((this: Window, ev: Event) => any) | null
    }

    const doc = document as unknown as {
      addEventListener: typeof document.addEventListener
      removeEventListener: typeof document.removeEventListener
    }

    const originalWinAdd = win.addEventListener.bind(win)
    const originalWinRemove = win.removeEventListener.bind(win)
    const originalDocAdd = doc.addEventListener.bind(doc)
    const originalDocRemove = doc.removeEventListener.bind(doc)

    // 将对 `unload` 的监听重定向为 `pagehide`，避免 Permissions-Policy 限制
    win.addEventListener = (type: any, listener: any, options?: any) => {
      if (type === 'unload')
        return originalWinAdd('pagehide', listener, options)
      return originalWinAdd(type, listener, options)
    }
    win.removeEventListener = (type: any, listener: any, options?: any) => {
      if (type === 'unload')
        return originalWinRemove('pagehide', listener, options)
      return originalWinRemove(type, listener, options)
    }

    doc.addEventListener = (type: any, listener: any, options?: any) => {
      if (type === 'unload')
        return originalDocAdd('pagehide', listener, options)
      return originalDocAdd(type, listener, options)
    }
    doc.removeEventListener = (type: any, listener: any, options?: any) => {
      if (type === 'unload')
        return originalDocRemove('pagehide', listener, options)
      return originalDocRemove(type, listener, options)
    }

    // 兼容使用 window.onunload = fn 的场景，改为在 pagehide 上触发
    try {
      Object.defineProperty(win, 'onunload', {
        configurable: true,
        enumerable: false,
        get() {
          return null
        },
        set(handler: any) {
          if (handler)
            originalWinAdd('pagehide', handler)
        },
      })
    } catch {}
  }
})


